<template>
  <div class="log-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>日志管理</span>
          <div class="header-actions">
            <el-button type="primary" @click="refreshLogs">刷新</el-button>
            <el-button type="success" @click="exportLogs">导出</el-button>
            <el-button type="warning" @click="cleanLogs">清理</el-button>
          </div>
        </div>
      </template>

      <!-- 统计信息 -->
      <el-row :gutter="20" class="statistics-row">
        <el-col :span="6">
          <el-card shadow="hover" class="stat-card">
            <div class="stat-content">
              <div class="stat-icon">
                <el-icon color="#409EFF" size="24"><i-ep-document /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-value">{{ statistics.total || 0 }}</div>
                <div class="stat-label">总日志数</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="stat-card">
            <div class="stat-content">
              <div class="stat-icon">
                <el-icon color="#67C23A" size="24"><i-ep-sunny /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-value">{{ statistics.today || 0 }}</div>
                <div class="stat-label">今日日志</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="stat-card">
            <div class="stat-content">
              <div class="stat-icon">
                <el-icon color="#E6A23C" size="24"><i-ep-warning /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-value">{{ statistics.thisWeek || 0 }}</div>
                <div class="stat-label">本周日志</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="stat-card">
            <div class="stat-content">
              <div class="stat-icon">
                <el-icon color="#F56C6C" size="24"><i-ep-error /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-value">{{ statistics.thisMonth || 0 }}</div>
                <div class="stat-label">本月日志</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 筛选工具栏 -->
      <div class="filter-toolbar">
        <el-row :gutter="16">
          <el-col :span="6">
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              style="width: 100%"
              @change="handleDateChange"
            />
          </el-col>
          <el-col :span="4">
            <el-select v-model="selectedLevel" placeholder="日志级别" clearable style="width: 100%">
              <el-option label="全部" value="" />
              <el-option label="信息" value="INFO" />
              <el-option label="警告" value="WARNING" />
              <el-option label="错误" value="ERROR" />
              <el-option label="调试" value="DEBUG" />
            </el-select>
          </el-col>
          <el-col :span="4">
            <el-input v-model="searchKeyword" placeholder="搜索用户名/操作" clearable />
          </el-col>
          <el-col :span="4">
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-col>
        </el-row>
      </div>

      <!-- 日志表格 -->
      <el-table :data="pagedLogs" style="width: 100%" v-loading="loading" stripe>
        <el-table-column prop="username" label="用户名" width="120" />
        <el-table-column prop="action" label="操作" min-width="200">
          <template #default="{ row }">
            <el-tag :type="getLevelTagType(row.level)" size="small">
              {{ row.level || 'INFO' }}
            </el-tag>
            <span style="margin-left: 8px;">{{ row.action }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述" min-width="200" show-overflow-tooltip />
        <el-table-column prop="ipAddress" label="IP地址" width="120" />
        <el-table-column prop="createdAtFormatted" label="创建时间" width="160" />
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="viewLogDetail(row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          :page-size="pageSize"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          @current-change="handlePageChange"
          @size-change="handleSizeChange"
        />
      </div>
    </el-card>

    <!-- 日志详情弹窗 -->
    <el-dialog title="日志详情" v-model="detailVisible" width="700px">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="用户名">{{ selectedLog?.username }}</el-descriptions-item>
        <el-descriptions-item label="操作">{{ selectedLog?.action }}</el-descriptions-item>
        <el-descriptions-item label="级别">
          <el-tag :type="getLevelTagType(selectedLog?.level)" size="small">
            {{ selectedLog?.level || 'INFO' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="IP地址">{{ selectedLog?.ipAddress }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ selectedLog?.createdAtFormatted }}</el-descriptions-item>
        <el-descriptions-item label="用户代理" :span="2">{{ selectedLog?.userAgent }}</el-descriptions-item>
        <el-descriptions-item label="描述" :span="2">{{ selectedLog?.description }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <el-button @click="detailVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'

// 响应式数据
const loading = ref(false)
const logs = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(20)
const dateRange = ref([])
const selectedLevel = ref('')
const searchKeyword = ref('')
const detailVisible = ref(false)
const selectedLog = ref(null)
const statistics = ref({})

// 计算属性
const pagedLogs = computed(() => logs.value)

// 获取日志级别标签类型
const getLevelTagType = (level) => {
  switch (level) {
    case 'ERROR': return 'danger'
    case 'WARNING': return 'warning'
    case 'INFO': return 'success'
    case 'DEBUG': return 'info'
    default: return 'info'
  }
}

// 获取日志数据
const fetchLogs = async () => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value
    }

    if (dateRange.value && dateRange.value.length === 2) {
      params.startDate = dateRange.value[0].toISOString()
      params.endDate = dateRange.value[1].toISOString()
    }

    if (selectedLevel.value) {
      params.level = selectedLevel.value
    }

    if (searchKeyword.value) {
      params.username = searchKeyword.value
      params.action = searchKeyword.value
    }

    const res = await axios.get('http://localhost:5252/api/log/list', { params })
    
    if (res.data) {
      logs.value = res.data.logs || []
      total.value = res.data.total || 0
    }
  } catch (error) {
    console.error('获取日志失败:', error)
    ElMessage.error('获取日志失败: ' + (error.response?.data || error.message))
  } finally {
    loading.value = false
  }
}

// 获取统计信息
const fetchStatistics = async () => {
  try {
    const res = await axios.get('http://localhost:5252/api/log/statistics')
    if (res.data) {
      statistics.value = res.data
    }
  } catch (error) {
    console.error('获取统计信息失败:', error)
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchLogs()
}

// 重置
const handleReset = () => {
  dateRange.value = []
  selectedLevel.value = ''
  searchKeyword.value = ''
  currentPage.value = 1
  fetchLogs()
}

// 日期变化
const handleDateChange = () => {
  currentPage.value = 1
  fetchLogs()
}

// 分页变化
const handlePageChange = (page) => {
  currentPage.value = page
  fetchLogs()
}

// 页面大小变化
const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  fetchLogs()
}

// 刷新日志
const refreshLogs = () => {
  fetchLogs()
  fetchStatistics()
}

// 导出日志
const exportLogs = async () => {
  try {
    const params = {}
    if (dateRange.value && dateRange.value.length === 2) {
      params.startDate = dateRange.value[0].toISOString()
      params.endDate = dateRange.value[1].toISOString()
    }
    if (selectedLevel.value) {
      params.level = selectedLevel.value
    }

    const res = await axios.get('http://localhost:5252/api/log/export', { 
      params,
      responseType: 'blob'
    })

    if (res.status === 200) {
      const url = window.URL.createObjectURL(new Blob([res.data]))
      const link = document.createElement('a')
      link.href = url
      link.setAttribute('download', `logs_${new Date().toISOString().split('T')[0]}.csv`)
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      window.URL.revokeObjectURL(url)
      ElMessage.success('日志导出成功')
    }
  } catch (error) {
    console.error('导出日志失败:', error)
    ElMessage.error('导出日志失败: ' + (error.response?.data || error.message))
  }
}

// 清理日志
const cleanLogs = async () => {
  try {
    await ElMessageBox.confirm('确定要清理30天前的日志吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const beforeDate = new Date()
    beforeDate.setDate(beforeDate.getDate() - 30)

    const res = await axios.delete('http://localhost:5252/api/log/clean', {
      params: { beforeDate: beforeDate.toISOString() }
    })

    if (res.status === 200) {
      ElMessage.success('日志清理成功')
      fetchLogs()
      fetchStatistics()
    }
  } catch (error) {
    if (error.message !== 'cancel') {
      console.error('清理日志失败:', error)
      ElMessage.error('清理日志失败: ' + (error.response?.data || error.message))
    }
  }
}

// 查看日志详情
const viewLogDetail = (row) => {
  selectedLog.value = row
  detailVisible.value = true
}

// 组件挂载时获取数据
onMounted(() => {
  fetchLogs()
  fetchStatistics()
})
</script>

<style scoped>
.log-management {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.statistics-row {
  margin-bottom: 20px;
}

.stat-card {
  height: 100px;
}

.stat-content {
  display: flex;
  align-items: center;
  height: 100%;
}

.stat-icon {
  margin-right: 16px;
}

.stat-info {
  flex: 1;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.filter-toolbar {
  margin-bottom: 20px;
  padding: 16px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}
</style> 